//- Copyright (C) 2023 Beijing Huaxia Chunsong Technology Co., Ltd. 
//- <https://www.chatopera.com>, Licensed under the Chunsong Public 
//- License, Version 1.0  (the "License"), https://docs.cskefu.com/licenses/v1.html
//- Unless required by applicable law or agreed to in writing, software
//- distributed under the License is distributed on an "AS IS" BASIS,
//- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//- See the License for the specific language governing permissions and
//- limitations under the License.
//- Copyright (C) 2018-Jun. 2023 Chatopera Inc, <https://www.chatopera.com>
//- Licensed under the Apache License, Version 2.0
//- http://www.apache.org/licenses/LICENSE-2.0
doctype html
html
    head
        meta(charset='utf-8')
        meta(http-equiv='Cache-Control', content='no-siteapp')
        meta(name='viewport', content='width=device-width,maximum-scale=1,initial-scale=1,initial-scale=1,user-scalable=no')
        meta(name='apple-mobile-web-app-capable', content='yes')
        title 智能客服
        if systemConfig != null && systemConfig.favlogo != null
            link(rel='shortcut icon', type='image/x-icon', href='/res/image.html?id=' + systemConfig.favlogo)
        else
            link(rel='shortcut icon', type='image/x-icon', href='/images/favicon.ico?t=1489039620156')
        link(rel='stylesheet', type='text/css', href='/im/css/ukefu.css')
        link#skin(rel='stylesheet', type='text/css', href='/im/css/default/ukefu.css')
        //- telemetry
        include telemetry
        //-  kindeditor
        link(rel='stylesheet', type='text/css', href='/im/js/kindeditor/themes/default/default.css')
        script(type='text/javascript', src='/js/jquery-1.10.2.min.js')
        script(src='/js/jquery.form.js')
        script(type='text/javascript', src='/im/js/kindeditor/kindeditor.js')
        script(type='text/javascript', src='/im/js/kindeditor/lang/zh-CN.js')
        style.
            * {
                -webkit-box-sizing: border-box;
                -moz-box-sizing: border-box;
                box-sizing: border-box;
                -webkit-tap-highlight-color: transparent;
                outline: none;
            }

            *:not(input,textarea) {
                -webkit-touch-callout: none;
            }

            #above:after {
                content: "";
                height: 100px;
                display: block;
            }

        script(src='/im/js/socket.io.js')
        script(src='/im/js/dayjs.min.js')
        script(type='text/javascript').
            var editor, words, textheight, wordinx = 0;

            /**
             * 文本框根据输入内容自适应高度
             * @param                {HTMLElement}        输入框元素
             * @param                {Number}                设置光标与输入框保持的距离(默认0)
             * @param                {Number}                设置最大高度(可选)
             */
            var autoTextarea = function (elem, extra, maxHeight) {
                extra = extra || 0;
                var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
                    isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
                    addEvent = function (type, callback) {
                        elem.addEventListener ?
                            elem.addEventListener(type, callback, false) :
                            elem.attachEvent('on' + type, callback);
                    },
                    getStyle = elem.currentStyle ? function (name) {
                        var val = elem.currentStyle[name];

                        if (name === 'height' && val.search(/px/i) !== 1) {
                            var rect = elem.getBoundingClientRect();
                            return rect.bottom - rect.top -
                                parseFloat(getStyle('paddingTop')) -
                                parseFloat(getStyle('paddingBottom')) + 'px';
                        }
                        ;

                        return val;
                    } : function (name) {
                        return getComputedStyle(elem, null)[name];
                    },
                    minHeight = parseFloat(getStyle('height'));


                elem.style.resize = 'none';

                var textchange = function () {
                    changeTextArea(0);
                }

                var change = function () {
                    changeTextArea(0);
                    wordinx = getPositionForTextArea(document.getElementById('message'));
                };

                addEvent('propertychange', textchange);
                addEvent('input', textchange);
                addEvent('focus', function () {
                    changeTextArea(0);
                });
                change();
            };
            //多行文本框
            function getPositionForTextArea(ctrl) {
                var CaretPos = 0;
                if (document.selection) { // IE Support
                    ctrl.focus();
                    var Sel = document.selection.createRange();
                    var Sel2 = Sel.duplicate();
                    Sel2.moveToElementText(ctrl);
                    var CaretPos = -1;
                    while (Sel2.inRange(Sel)) {
                        Sel2.moveStart('character');
                        CaretPos++;
                    }
                } else if (ctrl.selectionStart || ctrl.selectionStart == '0') { // Firefox support
                    CaretPos = ctrl.selectionStart;
                }
                return (CaretPos);
            }

            function openFaceDialog() {
                if (document.getElementById("faceindex").style.display == "none") {
                    document.getElementById("faceindex").style.display = "block";
                    document.getElementById("bottom").style.height = $('#message').height() + 20 + document.getElementById("faceindex").offsetHeight + "px";
                    document.getElementById("above").style.height = "calc(100% - " + ($('#bottom').height()) + "px)"
                } else {
                    closeFaceDialog(0);
                }
                return false;
            }

            function closeFaceDialog(height) {
                document.getElementById("faceindex").style.display = "none";
                document.getElementById("bottom").style.height = $('#message').height() + height + "px";
                document.getElementById("above").style.height = "calc(100% - " + ($('#message').height()) + "px)";
            }

            function changeTextArea(height) {
                if (document.getElementById("faceindex").style.display == "none") {
                    $('#bottom').height($('#message').height() + height);
                    document.getElementById("above").style.height = "calc(100% - " + ($('#message').height()) + "px)"
                } else {
                    $('#bottom').height($('#message').height() + $('#faceindex').height());
                    document.getElementById("above").style.height = "calc(100% - " + ($('#message').height()) + "px)"
                }
            }
            function insertImg(obj) {
                if (wordinx >= 0) {
                    var text = $('#message').val();
                    var value = text.substring(0, wordinx) + "[" + obj + "]" + text.substring(wordinx, text.length);
                    $('#message').val(value);
                    wordinx = wordinx + 2 + obj.length;
                }
            }
            $(document).ready(function () {
                window.addEventListener('resize', function () {
                    if (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA') {
                        window.setTimeout(function () {
                            document.activeElement.scrollIntoViewIfNeeded()
                        }, 0)
                    }
                });
                // 在输入框获取焦点, 键盘弹起后, 真的是一行代码

                $(document).on('submit.form.data-api', '[data-toggle="ajax-form"]', function (e) {
                    var formValue = $(e.target);
                    $(this).ajaxSubmit({
                        url: formValue.attr("action"),
                        success: function (data) {

                        },
                        error: function (xhr, type, s) {
                            //notification("",false);	//结束
                        }
                    });
                    return false;
                });
            });

        //  kindeditor 
    body.ukefu-im-theme.ukefu-point-text(style='width:100%;overflow:hidden;height:100%;max-height:100%;position: fixed;/* 或者scroll */-webkit-overflow-scrolling: touch;/* 解决ios滑动不流畅问题 */')
        - var dialog_headimg= inviteData.consult_dialog_headimg ? '/res/image.html?id=' + inviteData.consult_dialog_headimg : '/images/agent.png'
        #header(class="theme" + inviteData.consult_dialog_color)
            img(src=(inviteData.consult_dialog_logo ? '/res/image.html?id=' + inviteData.consult_dialog_logo : '/images/logo.png'), style='height:50px;padding:10px;')
            .ukefu-func-tab
                ul
                    if models.contains("chatbot") && inviteData.ai && inviteData.ai == true && aiid
                        li
                            a(href="/im/index.html?appid=" + appid + (aiid ? '&aiid=' + aiid : '') + "&ai=true" + (client ? '&client=' + client : '') + (type ? '&type=' + type : '') + (skill ? '&skill=' + skill : '') + (agent ? '&agent=' + agent : '') + "&userid=" + userid + "&sessionid=" + sessionid + "&t=" + pugHelper.currentTimeMillis()) 智能客服
                        li.cur
                            a(href="javascript:void(0)") 人工坐席
                    else
                        li.cur
                            a(href="javascript:void(0)") 人工坐席
        #cooperation.ukefu-cooperation(style='display:none;z-index: 100;background-color: #ffffff;position: fixed;left: 0px;width: 100%;top: 0px;top:0px;height: 100%;')
            .ukefu-image-canvas#ukefu-image-content(style='margin-top:2px;')
                img#ukefu_img_ctx(style='max-width: 100%;max-height: 100%;')
            .drawBoard(style='position: absolute;left: 0;top: 0;margin-top:2px;z-index: 998;')
                canvas#canvas-borad.brushBorad 你的浏览器不支持 canvas 绘图
            div(style='position: absolute;bottom: 10px;width: 100%;text-align: center;z-index:10000')
                button#offcoop-btn(style='border-color:#009688 !important;color:#FFFFFF;display: inline-block;height: 38px;line-height: 38px;padding: 0 18px;background-color: #009688;color: #fff;white-space: nowrap;text-align: center;font-size: 14px;margin-right:10px;border: none;border-radius: 2px;cursor: pointer;opacity: .9;filter: alpha(opacity=90);background-color: #377FED !important;border:1px solid #FFFFFF;', onclick='offCoop();') 退出协作
        .chat-above#above
            if welcomeAd
                .clearfix.message.welcome
                    span#welcome-messa
                        if welcomeAd.adtype == "image"
                            div(style="text-align: center")
                                a(href=welcomeAd.url, title=welcomeAd.tiptext, target="_blank")
                                    img(src=welcomeAd.imgurl, style="max-width:420px;max-height:178px;margin:0px;vertical-align: middle;")
                        else
                            div(style="padding:0px 5px 10px 5px;border-bottom:1px solid #dedede;")
                                a#point_ad_text(href=welcomeAd.url, title=welcomeAd.tiptext, target="_blank")= welcomeAd.content
            .clearfix.message.welcome
                span#welcome-message= inviteData.dialog_message ? inviteData.dialog_message : '欢迎您来咨询！欢迎使用 Chatopera 云服务！如需帮助请联系 info@chatopera.com'
            for chatMessage in pugHelper.reverse(chatMessageList.content)
                if chatMessage.userid && userid && chatMessage.calltype && chatMessage.calltype == "呼入"
                    .clearfix.chat-block
                        .chat-right
                            img.user-img(src="/im/img/user.png", alt="")
                            .chat-message
                                label.time= pugHelper.formatDate('yyyy-MM-dd HH:mm:ss', chatMessage.createtime)
                                label.user #{chatMessage.username}
                            .chatting-right
                                i.arrow(class="arrow" + inviteData.consult_dialog_color)
                                .chat-content(class="theme" + inviteData.consult_dialog_color)
                                    include media/message
                else
                    .clearfix.chat-block
                        .chat-left
                            img.user-img(src=dialog_headimg, alt="")
                            .chat-message
                                label.user= chatMessage.chatype && chatMessage.chatype == 'aireply' ? (inviteData.ainame ? inviteData.ainame : '小松') : chatMessage.username
                                label.time= pugHelper.formatDate('yyyy-MM-dd HH:mm:ss', chatMessage.createtime)
                            .chatting-left
                                i.arrow
                                .chat-content
                                    include media/message
        .mobile-chat-bottom#bottom
            form#imgForm(action='/im/image/upload.html?userid=' + userid + '&appid=' + appid + '&username=' + username, data-toggle='ajax-form', enctype='multipart/form-data')
                a.imgFile(href='javascript:;', onclick='closeFaceDialog(0)')
                    img.chat-type(src='/im/img/img.png', style='width:32px;height:32px;')
                    input#imgFile(type='file', name='imgFile', accept='image/*', onchange='$(\'#imgForm\').submit();$(this).val(\'\');')
            img#evaluation(onclick='popup(\'block\')', src='/im/img/evaluationm.png', style='width:32px;height:32px;    margin-left: 40px;margin-top: 5px;')
            textarea#message(name='content', maxlength=(inviteData.maxwordsnum > 0 ? inviteData.maxwordsnum : 300))
            .btn-push.clearfix
                img#facedialog(onclick='return openFaceDialog()', src='/im/img/face.png', style='width:32px;height:32px;')
                a(href='javascript:void(0)', onclick='sendMessage();return false;')
                    img(src='/im/img/send.png', style='width:32px;height:32px;')
            #faceindex(style='display:none;height:200px;position: absolute;bottom: 0px;width:100%;overflow-x:auto;')
                table.ke-table(cellpadding='0', cellspacing='0', border='0', style='min-width:100%;')
                    tbody
                        for row in pugHelper.range(0,4)
                            tr
                                for col in pugHelper.range(0,20)
                                    - var emoid=row * 20 + col;
                                    td.ke-cell
                                        span.ke-img
                                            img(src="/im/js/kindeditor/plugins/emoticons/images/" + emoid + ".png", border="0", alt="", onclick="insertImg('" + emoid + "')")

        //- 调查问卷弹框
        if sessionConfig.satisfaction
            .dialogWrap#dialogWrap(style='display: none;height: auto;margin:0px;top:0;left: 0;border:none;width: 100%;height: 100%;background-color:#fff;overflow: auto')
                .dialogCon
                    form#commentContent(onsubmit='return submitForm(this)')
                        input#agentserviceid(type='hidden', name='id')
                        div(style='width: 100%;height: 100%;overflow:auto;')
                            h2.diaHeader.clearfix(style='width: 90%;margin: 0 auto;')
                                span 评价
                                hr(style='width: 100%;')
                            p.title(style='width: 90%;margin: 10px auto 0;') 您是否对此次服务满意?
                            // 评价
                            div(style='width: 90%;margin: 20px auto')
                                span(style='font-weight: 600;font-size: 16px;') 评价：
                                span(style='position: relative;top: 10px')
                                    div(style='width: 100%;height: auto;margin-bottom: 15px')
                                        - var defaultvalue = "";
                                        for comment in commentList
                                            - defaultvalue = comment.code;
                                            div(style="margin-bottom:15px;width: 188px")
                                                input(type="radio",checked=comment_index == 0, name="satislevel", value=comment.code, id="dic_" + comment.id, onclick="document.getElementById('satislevel_input').value = this.value")
                                                label.radio(for="dic_" + comment.id)= comment.name
                                        input#satislevel_input(type="hidden", name="t", value=defaultvalue)

                            div(style='width: 90%;margin: 20px auto')
                                span(style='font-weight: 600;font-size: 16px;') 意见：
                                input#comment_input(type='hidden', name='t')
                                span(style='position: relative;top: 10px')
                                    div(style='width: 100%;height: auto;margin-bottom: 15px')
                                        for item in commentItemList
                                            div(style="margin-bottom:15px;width: 188px")
                                                input(type="radio", name="comment", id="item_" + item.id, value=item.id, contentname=item.name, onclick="selectOther(this.getAttribute('contentname'),this.value)")
                                                label.radio(for="item_" + item.id, style="margin-right: 0px")= item.name
                                        textarea#othertxt.layui-textarea(name="comment", placeholder="请输入意见(最大长度为200个字符)", style="resize:none;display: none;height: 85px; width:100%;background: #f7f7f7;border-color: #ccc;font-size: 14px;outline: none;padding-left: 10px;border-radius: 2px;", maxlength="200")
                            div(style='width: 100%;height: 85px')
                            // 按钮
                            p.submitBtnWrap(style='background:#fff;position: fixed;bottom: 0px;left:0px;width: 100%;height:100px;padding-right: 0px;margin-bottom: 0px;z-index: 10')
                                input.btn.submitBtn#submitBtn(type='submit', style='width: 85% !important;display: block;margin: 0 auto;', value='提 交')
        script.
            var service_end = false;
            // 调查问卷
            var dialogWrap = document.getElementById('dialogWrap');
            function popup(para) {
                dialogWrap.style.display = para;
            }
            function chatScorllBottom(box) {
                var imgdefereds = [];  					//定义一个操作数组
                $('#' + box + ' .ukefu-media-image').each(function () {  	//遍历所有图片，将图片
                    var dfd = $.Deferred();  				//定义一个将要完成某个操作的对象
                    $(this).bind('load', function () {
                        dfd.resolve();  			//图片加载完成后，表示操作成功
                    });
                    if (this.complete) {				//如果图片加载状态为完成，那么也标识操作成功
                        setTimeout(function () {
                            dfd.resolve();
                        }, 1000);
                    }
                    imgdefereds.push(dfd);  			//将所有操作对象放入数组中
                })
                $.when.apply(null, imgdefereds).done(function () {  	//注册所有操作完成后的执行方法
                    document.getElementById(box).scrollTop = document.getElementById(box).scrollHeight
                });
            }

            chatScorllBottom("above");
            function selectOther(name, value) {
                var otherTxt = document.getElementById('othertxt');
                if (name == "其他") {
                    otherTxt.style.display = "block"
                } else {
                    otherTxt.style.display = "none";
                }
                document.getElementById("comment_input").value = value;
            }

            var R3Ajax = {
                ajax: function (opt) {
                    var xhr = this.createXhrObject();
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState != 4) return;
                        (xhr.status === 200 ?
                            opt.success(xhr.responseText, xhr.responseXML) :
                            opt.error(xhr.responseText, xhr.status));
                    }
                    xhr.open(opt.type, opt.url, true);
                    if (opt.type !== 'post')
                        opt.data = null;
                    else
                        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    opt.data = this.parseQuery(opt.data);
                    xhr.send(opt.data);
                },
                post: function (url, success, data) {
                    var popt = {
                        url: url,
                        type: 'post',
                        data: data,
                        success: success,
                        error: function (data) {
                        }
                    }
                    this.ajax(popt);
                },
                get: function (url, success) {
                    var gopt = {
                        url: url,
                        type: 'get',
                        success: success,
                        error: function () {
                        }
                    }
                    this.ajax(gopt);
                },
                createXhrObject: function () {
                    var methods = [
                        function () {
                            return new XMLHttpRequest();
                        },
                        function () {
                            return new ActiveXObject('Msxml2.XMLHTTP');
                        },
                        function () {
                            return new ActiveXObject('Microsoft.XMLHTTP');
                        }
                    ];
                    for (var i = 0; len = methods.length, i < len; i++) {
                        try {
                            methods[i]();
                        } catch (e) {
                            continue;
                        }
                        this.createXhrObject = methods[i];
                        return methods[i]();
                    }
                    throw new Error('Could not create an XHR object.');
                },
                parseQuery: function (json) {
                    if (typeof json == 'object') {
                        var str = '';
                        for (var i in json) {
                            str += "&" + i + "=" + encodeURIComponent(json[i]);
                        }
                        return str.length == 0 ? str : str.substring(1);
                    } else {
                        return json;
                    }
                },
                audioplayer: function (id, file, loop) {
                    var audioplayer = document.getElementById(id);
                    if (audioplayer != null) {
                        document.body.removeChild(audioplayer);
                    }

                    if (typeof (file) != 'undefined') {
                        if (navigator.userAgent.indexOf("MSIE") > 0) { // IE
                            var player = document.createElement('bgsound');
                            player.id = id;
                            player.src = file['mp3'];
                            player.setAttribute('autostart', 'true');
                            if (loop) {
                                player.setAttribute('loop', 'infinite');
                            }
                            document.body.appendChild(player);

                        } else { // Other FF Chome Safari Opera
                            var player = document.createElement('audio');
                            player.id = id;
                            player.setAttribute('autoplay', 'autoplay');
                            if (loop) {
                                player.setAttribute('loop', 'loop');
                            }
                            document.body.appendChild(player);

                            var mp3 = document.createElement('source');
                            mp3.src = file['mp3'];
                            mp3.type = 'audio/mpeg';
                            player.appendChild(mp3);
                        }
                    }
                }
            };

            function submitForm(form) {
                var satisComment = "";
                var otherVal = document.getElementById('othertxt').value;
                var comInputVal = document.getElementById("comment_input").value;
                if (otherVal.length > 0) {
                    satisComment = otherVal;
                } else {
                    satisComment = comInputVal;
                }
                R3Ajax.post("/im/satis.html", function () {
                    document.getElementById("dialogWrap").style.display = "none";
                    alert("服务评价已提交");
                }, "id=" + form.id.value + "&satislevel=" + document.getElementById("satislevel_input").value + "&satiscomment=" + encodeURIComponent(satisComment));
                return false;
            }

            // 参数连接
            // 参数连接
            var hostname = location.hostname;
            var protocol = window.location.protocol.replace(/:/g, '');
            var username = encodeURIComponent("#{username}");
            var socket = io(protocol + '://' + hostname + ':#{port}/im/user?userid=#{userid}&session=#{sessionid}&appid=#{appid}&osname=!{osname}&browser=!{browser}!{skill ? "&skill=" + skill : ""}!{username ? "&nickname='+username+'" : ""}!{agent ? "&agent=" + agent : ""}!{title ? "&title=" + title : ""}!{traceid ? "&url=" + url : ""}!{traceid ? "&traceid=" + traceid : ""}!{isInvite ? "&isInvite=" + isInvite : ""}', {transports: ['websocket', 'polling']});
            socket.on('connect', function () {
                if ('#{contacts.name}') {
                    socket.emit('new', {
                        name: "#{contacts.name}",
                        phone: "#{contacts.phone}",
                        email: "#{contacts.email}",
                        memo: "#{contacts.memo}",
                        appid: "#{appid}"
                    });
                }
                //service.sendRequestMessage();
                //output('<span id="callOutConnect-message">'+ new Date().format("yyyy-MM-dd hh:mm:ss") + ' 开始沟通' +'</span>' , 'message callOutConnect-message');
            })
            socket.on("agentstatus", function (data) {
                document.getElementById('connect-message').innerHTML = data.message;
            })
            socket.on("status", function (data) {
                output('<span id="connect-message">' + data.message + '</span>', 'message connect-message');
                if (data.messageType == "end") {
                    service_end = true;
                    //editor.readonly();
                } else {
                    service_end = false;
                }
                if (document.getElementById("agentserviceid")) {
                    document.getElementById("agentserviceid").value = data.agentserviceid;
                }
            })
            socket.on('message', function (data) {
                var chat = document.getElementsByClassName('chatting-left').innerText;
                data.createtime = dayjs(data.createtime).format('YYYY-MM-DD HH:mm:ss');
                chat = data.message;
                if (data.msgtype == "image") {
                    chat = "<a href='" + data.message + "&original=true' target='_blank'><img src='" + data.message + "' class='ukefu-media-image'/></a>";
                } else if (data.msgtype == "file") {
                    chat = "<div class='ukefu-message-file'><div class='ukefu-file-icon'><img src='/im/img/file.png'></div><div class='ukefu-file-desc'><a href='" + data.message + "' target='_blank'><div>" + data.filename + "</div><div>" + (data.filesize / 1024).toFixed(3) + "Kb</div></a></div></div>";
                } else if (data.msgtype == "cooperation") {
                    chat = "<a href='javascript:void(0)' onclick='acceptInvite(\"" + data.message + "\", \"" + data.attachmentid + "\")'>您收到一个协作邀请，点击进入协作</a>";
                } else if (data.msgtype == "action") {
                    //检查访客是否在协作页面上，如果在协作页面上，就开始执行重绘，否则不做处理
                    drawCanvasImage(data.attachmentid);
                }
                if (data.calltype == "呼入") {
                    output('<div class="chat-right"> <img class="user-img" src="/im/img/user.png" alt=""><div class="chat-message"><label class="time">' + data.createtime + '</label><label  class="user">' + data.username + '</label> </div><div class="chatting-right"><i class="arrow arrow#{inviteData.consult_dialog_color}"></i><div class="chat-content theme#{inviteData.consult_dialog_color}">' + chat + '</div></div>', "chat-block", data.msgtype);
                } else if (data.calltype == "呼出") {
                    output('<div class="chat-left"> <img class="user-img" src="#{dialog_headimg}" alt=""><div class="chat-message"><label  class="user">' + data.username + '</label><label class="time">' + data.createtime + '</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content">' + chat + '</div></div>', "chat-block", data.msgtype);
                }
            });

            socket.on('satisfaction', function () {
                if ('#{sessionConfig.satisfaction}')
                    popup('block');
            });

            socket.on('disconnect', function () {
                output('<span id="connect-message">连接坐席失败，在线咨询服务不可用</span>', 'message connect-message');
            });
            function sendDisconnect() {
                socket.disconnect();
            }
            function acceptInvite(msgid, fileid) {
                document.getElementById("cooperation").style.display = "block";
                document.getElementById("ukefu_img_ctx").src = "/res/image.html?id=" + fileid + "&cooperation=true&original=true";

                $("#ukefu_img_ctx").load(function () {
                    var height = document.getElementById("ukefu-image-content").offsetHeight;
                    var width = document.getElementById("ukefu-image-content").offsetWidth;
                    var canvas = document.getElementById("canvas-borad");
                    if (canvas.getContext) {
                        canvas.width = width;
                        canvas.height = height;

                        drawCanvasImage(fileid);
                    }

                });
            }
            function drawCanvasImage(fileid) {
                var canvas = document.getElementById("canvas-borad");

                if (canvas.getContext && document.getElementById("cooperation").style.display == "block") {
                    var ctx = canvas.getContext("2d");

                    //创建新的图片对象
                    var img = new Image();
                    //指定图片的URL
                    img.src = "/res/image.html?id=" + fileid + "&cooperation=true&original=true";
                    //浏览器加载图片完毕后再绘制图片
                    img.onload = function () {
                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                        //以Canvas画布上的坐标(10,10)为起始点，绘制图像
                        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                    };
                }
            }
            function offCoop() {
                document.getElementById("cooperation").style.display = "none";
            }
            function sendMessage() {
                var count = document.getElementById('message').value.length;
                if (count > 0 && service_end == false) {
                    var message = $("#message").val();
                    sendMessageText(message);
                    $("#message").val("");
                    wordinx = 0;
                } else if (service_end == true) {
                    alert("服务器已断开和您的对话");
                }
                closeFaceDialog(0);
            }
            function sendMessageText(message) {
                if (message != "") {
                    socket.emit('message', {
                        appid: "#{appid}",
                        userid: "#{userid}",
                        username: "#{username}",
                        channel: "webim",
                        type: "message",
                        contextid: "#{sessionid}",
                        message: message
                    });
                }
            }
            function output(message, clazz, msgType) {
                if (clazz == "message connect-message") {
                    var messages = document.getElementsByClassName("connect-message");
                    for (inx = 0; inx < messages.length;) {
                        document.getElementById('above').removeChild(messages[inx]);
                        inx++;
                    }
                }
                var element = ("<div class='clearfix " + clazz + "'>" + " " + message + "</div>");
                document.getElementById('above').innerHTML = (document
                    .getElementById('above').innerHTML + element);

                if (msgType && msgType == "image") {
                    chatScorllBottom("above")
                } else {
                    document.getElementById("above").scrollTop = document.getElementById("above").scrollHeight
                }
                //$("#welcome-message").html(document.getElementById('above').scrollHeight);
            }
            function update(id, message) {
                document.getElementById(id).innerHTML = message;
            }
            autoTextarea(document.getElementById("message"));// 调用
            $('#message').click(function () {
                wordinx = getPositionForTextArea(document.getElementById('message'));
                closeFaceDialog(0);
            });

            var message = {
                // text:data.message,
                // picture:function(){

                // }
                // file:function(){

                // }
                // lang:function(){

                // }
                // goods:function(){

                // }
                // POI:function(){

                // }

            }
            
